package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	"os/exec"
	"regexp"
	"runtime"
	"strings"
)

func executeRebuildRepo(dir string) error {
	out, err := exec.Command("rm", "-rf", fmt.Sprintf("%s/repodata", dir)).Output()

	if err != nil {
		return err
	}

	out, err = exec.Command("/usr/bin/createrepo", "-pdo", dir, dir).Output()

	if err != nil {
		return err
	}

	// fmt.Println("Command Successfully Executed")

	output := string(out[:])

	fmt.Println(output)

	return nil
}

// rebuildCmd represents the rebuild command
var rebuildCmd = &cobra.Command{
	Use:   "rebuild",
	Short: "A brief description of your command",
	Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
	Run: func(cmd *cobra.Command, args []string) {
		re := regexp.MustCompile("[-,]+")

		for _, v1 := range AppConfig.Yum.Repos {
			releasevers := re.Split(v1.Releasever, -1)

			for _, el := range releasevers {
				dirPath := strings.ReplaceAll(strings.ReplaceAll(v1.Dir, "{version}", v1.Version), "{releasever}", el)
				storeDir := fmt.Sprintf("%s/%s", AppConfig.Yum.StoreDir, dirPath)

				// fmt.Println(storeDir)

				if runtime.GOOS == "windows" {
					fmt.Println("Can't Execute this on a windows machine")
				} else {
					err := executeRebuildRepo(storeDir)

					if err != nil {
						fmt.Println(fmt.Sprintf("ERROR: %s", err.Error()))
					} else {
						fmt.Println(fmt.Sprintf("\033[1;32mRebuild\033[0m. (%s)", storeDir))
					}
				}
			}
		}
	},
}

func init() {
	rootCmd.AddCommand(rebuildCmd)

	rebuildCmd.Flags().Bool("help", false, "Show help.")

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// rebuildCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// rebuildCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
